package com.demo2do.core.redis.web.taglib;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.demo2do.core.redis.RedisAccessor;

/**
 * Redis Tag renders redis data access on JSP
 *
 * @author Carl Jiang
 *
 */
public class RedisTag extends BodyTagSupport {

    private static final Log logger = LogFactory.getLog(RedisTag.class);

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -9002831087322134048L;

    /**
     * redis key
     */
    private String key;

    /**
     * data type
     */
    private String type;

    private RedisAccessor redisAccessor;

    /**
     * default constructor
     */
    public RedisTag() {
    }

	public void init() {
    	redisAccessor = WebApplicationContextUtils.getRequiredWebApplicationContext(pageContext.getServletContext()).getBean(RedisAccessor.class);
	}

	public int doStartTag() throws JspException {

		init();

        JspWriter writer = pageContext.getOut();

        try {
        	if(type == null)
        		writer.write(redisAccessor.evaluate(key));
        	else if("int".equals(type))
        		writer.write(Integer.toString(redisAccessor.evaluateAsInt(key)));
        } catch (IOException e) {
            logger.error(e);
        }

        return EVAL_BODY_INCLUDE;
    }

	/**
	 * @return the key
	 */
	public String getKey() {
		return key;
	}

	/**
	 * @return the type
	 */
	public String getType() {
		return type;
	}

	/**
	 * @param key the key to set
	 */
	public void setKey(String key) {
		this.key = key;
	}

	/**
	 * @param type the type to set
	 */
	public void setType(String type) {
		this.type = type;
	}

}
 